//
//  GroupListVC.m
//  wanzhaoIM
//
//  Created by liuyuantao on 15/5/11.
//  Copyright (c) 2015年 liuyuantao. All rights reserved.
//

#import "GroupListVC.h"

#import "SettingNormalCell.h"
#import "MicroDef.h"
#import "GroupDetailVC.h"
#import "CGroupModel.h"
#import "CGroupMgr.h"
#import "GroupMenberCell.h"
#import "CHChatRoomBase.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "CDepartmentMgr.h"
#import "CDepartmentModel.h"
#import "UIImageView+WebCache.h"
#import "NSArray+PinYin.h"
#import "CXmppRequestMgr.h"
#import "GroupMemberDetailVC.h"
#import "NSArray+PinYin.h"
#import "IMSearchDisplayController.h"
#import "CFolderMgr.h"

#define KSECTIONHEIGHT 35.0f
#define KNORMALCELLHEIGHT 60.0f
@interface GroupListVC ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UISearchDisplayDelegate>
{
    UITableView *_tableView;
    UISearchBar *_searchBar;
    UISearchDisplayController *_searchDisplayController;
    NSMutableArray *_searchAllFirstLetter;
    NSMutableArray *_searchSectionListArray;

}

WeakProperty UIView *nolistView;

@property (nonatomic, strong) NSMutableArray *groupArray;
@property (nonatomic, strong) CGroupMgr *groupMgr;
@property (nonatomic, strong) NSMutableArray *mineGroupArray;
@property (nonatomic, strong) NSMutableArray *otherGroupArray;

@property (nonatomic, weak) UILabel *notgroupLabel;
@property (nonatomic, strong) CContactModel *curContact;
@end

@implementation GroupListVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:k_XMPPUPDATEGROUPLIST object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:k_XMPPGETGROUPLIST object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPUPDATEGROUPINFO object:nil];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (_searchDisplayController.active) {
        [_searchDisplayController setActive:NO];
    }

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (IsIOS7) {
        [self.navigationController.navigationBar setBarTintColor:RGBCOLOR(44, 170, 253)];
    } else {
        [self.navigationController.navigationBar setTintColor:RGBCOLOR(44, 170, 253)];
    }
    
    [self updateGroupList];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    if (IsIOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }

    
    // Do any additional setup after loading the view.
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    
    CAccountModel *model = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    self.curContact = [[[CContactMgr alloc] init] loadContactWithUserCode:model.userName];
    
    _searchAllFirstLetter = [NSMutableArray arrayWithCapacity:5];
    _searchSectionListArray = [NSMutableArray arrayWithCapacity:5];
    self.groupMgr = [[CGroupMgr alloc] init];
    
    [self.navigationItem setNewTitleCenter:@"群"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateGroupList) name:k_XMPPUPDATEGROUPLIST object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateGroupList) name:k_XMPPGETGROUPLIST object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateGroupList) name:K_XMPPUPDATEGROUPINFO object:nil];
    
    _tableView = [[UITableView alloc] init];
    _tableView.frame = CGRectMake(0, 44.0f, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 44.0f - 64.0f);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.sectionIndexBackgroundColor = ClearColor;
    _tableView.sectionIndexTrackingBackgroundColor = ClearColor;
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = ClearColor;
    
    
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
     _searchBar.backgroundImage = [UIImage imageNamed:@"BG-search"];
    _searchBar.placeholder = @"搜索";
    _searchBar.delegate = self;
    // 添加 searchbar 到 headerview
    [self.view addSubview:_searchBar];
    
    
    
    _searchDisplayController = [[IMSearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
    
    // searchResultsDataSource 就是 UITableViewDataSource
    _searchDisplayController.searchResultsDataSource = self;
    // searchResultsDelegate 就是 UITableViewDelegate
    _searchDisplayController.searchResultsDelegate = self;
    _searchDisplayController.delegate = self;
    _searchDisplayController.searchResultsTableView.sectionIndexColor = RGBCOLOR(0x64, 0x64, 0x64);
    _searchDisplayController.searchResultsTableView.sectionIndexBackgroundColor = ClearColor;
    _searchDisplayController.searchResultsTableView.sectionIndexTrackingBackgroundColor = ClearColor;

    self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    
    [self setupNoListView];
    //加载群组数据
    
    NSArray *array = [self.groupMgr loadAllGroup];
    if (array.count > 0) {
        NSArray *sortArray = [NSArray sortArray:array];
        
        for (CGroupModel *group in sortArray) {
            if ([group.OwnerId isEqualToString:self.curContact.UserID]) {
                [self.mineGroupArray addObject:group];
            } else {
                [self.otherGroupArray addObject:group];
            }
        }
        self.nolistView.hidden = YES;
        _tableView.hidden = NO;
        _searchBar.hidden = NO;
    } else {
        self.nolistView.hidden = NO;
        _searchBar.hidden = YES;
        _tableView.hidden = YES;
    }
    
}

- (void)setupNoListView
{
    UIView *view = [[UIView alloc] init];
    view.frame = CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 64.0f);
    [self.view addSubview:view];
    self.nolistView = view;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"BG-zero"] forState:UIControlStateNormal];
    button.userInteractionEnabled = NO;
    [view addSubview:button];
    button.frame = CGRectMake(0, 140.0f, HARDWARE_SCREEN_WIDTH, button.currentImage.size.height);
    
    UILabel *label = [[UILabel alloc] init];
    label.backgroundColor = ClearColor;
    label.textAlignment = UITextAlignmentCenter;
    label.font = Font16;
    label.textColor = RGBCOLORWITH16COLOR(0xb1b1b1);
    label.text = @"您还没有加入过群";
    label.frame = CGRectMake(0, CGRectGetMaxY(button.frame) + 15.0f, HARDWARE_SCREEN_WIDTH, Font16.lineHeight);
    [view addSubview:label];
    
}


- (void)updateGroupList
{
    [self.mineGroupArray removeAllObjects];
    [self.otherGroupArray removeAllObjects];
    
    NSArray *array = [self.groupMgr loadAllGroup];
    if (array.count > 0) {
        NSArray *sortArray = [NSArray sortArray:array];
        
        for (CGroupModel *group in sortArray) {
            if ([group.OwnerId isEqualToString:self.curContact.UserID]) {
                [self.mineGroupArray addObject:group];
            } else {
                [self.otherGroupArray addObject:group];
            }
        }
        self.nolistView.hidden = YES;
        _tableView.hidden = NO;
        _searchBar.hidden = NO;
    } else {
        self.nolistView.hidden = NO;
        _tableView.hidden = YES;
        _searchBar.hidden = YES;
    }

    [_tableView reloadData];
}
- (NSMutableArray *)groupArray
{
    if (_groupArray == nil) {
        _groupArray = [NSMutableArray array];
    }
    return _groupArray;
}

- (NSMutableArray *)mineGroupArray
{
    if (_mineGroupArray == nil) {
        _mineGroupArray = [NSMutableArray array];
    }
    return _mineGroupArray;
}
- (NSMutableArray *)otherGroupArray
{
    if (_otherGroupArray == nil) {
        _otherGroupArray = [NSMutableArray array];
    }
    return _otherGroupArray;
}
- (void)createNewGroup
{


}



#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if(tableView == _tableView)
    {
        if (section == 0) {
            if (self.mineGroupArray.count > 0) {
                return self.mineGroupArray.count;
            } else {
                return self.otherGroupArray.count;
            }
        } else if (section == 1) {
            return self.otherGroupArray.count;
        } else {
            return 0;
        }
    }
    else
    {
        NSArray *rowArray = _searchSectionListArray[section];
        return rowArray.count;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView              // Default is 1 if not implemented
{
    if(tableView == _tableView)
    {
        NSInteger section = 0;
        if (self.mineGroupArray.count > 0) {
            section ++;
        }
        if (self.otherGroupArray.count > 0) {
            section ++;
        }
        return section;
    }
    else
    {
        return _searchSectionListArray.count;
    }
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGroupModel *groupModel = nil;
    if(tableView == _tableView)
    {
        if (indexPath.section == 0) {
            if (self.mineGroupArray.count > 0) {
               groupModel = self.mineGroupArray[indexPath.row];
            } else {
                groupModel = self.otherGroupArray[indexPath.row];
            }
        } else {
            groupModel = self.otherGroupArray[indexPath.row];
        }
        
    } else {
        NSArray *rowArray = _searchSectionListArray[indexPath.section];
        groupModel = rowArray[indexPath.row];

    }
    
    static NSString *NormalCellIdentifier = @"SettingNormalCell";
    UITableViewCell *cell = nil;
    SettingNormalCell *normalCell = [tableView dequeueReusableCellWithIdentifier:NormalCellIdentifier];
    if (normalCell == nil) {
        normalCell = [[[NSBundle mainBundle] loadNibNamed:@"SettingNormalCell" owner:self options:nil] objectAtIndex:0];
    }
    
    [normalCell.icon setImage:[UIImage imageNamed:[self iconName:indexPath]] forState:UIControlStateNormal];
    normalCell.icon.layer.cornerRadius = 5.0f/2;
    normalCell.icon.layer.masksToBounds = YES;
    [normalCell.titleLabel setText:[NSString stringWithFormat:@"%@(%zd)",groupModel.GroupName,groupModel.UserNum]];
    [normalCell.seperatorLine setHidden:NO];
//    if(indexPath.section == 1 && indexPath.row == 0)
//    {
//    }
//    else
//    {
//        [normalCell.seperatorLine setHidden:YES];
//    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell = normalCell;
    return cell;
}


-(NSString *)iconName:(NSIndexPath *)indexPath
{
    NSString *iconName = nil;
    
    iconName = @"icon_groupList";
    return iconName;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (_tableView == tableView) {
        return nil;
    } else{
        return _searchAllFirstLetter;
    }
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    NSInteger count = 0;
    if(tableView == _tableView)
    {
        
    } else {
        count = index;
    }
    return count;
}




#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
  return KSECTIONHEIGHT;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
//    CGFloat height = 0;
//    switch (section) {
//        case 0:
//            height = 0.01f;
//            break;
//        default:
//            break;
//    }
    return 0.01f;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section   // custom view for header. will be adjusted to default or specified header height
{
    
    UIView *headerView = nil;
//    if(section == 0)
//    {
//        return headerView;
//    }
    headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, KSECTIONHEIGHT);
    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    UIView *beginLine = [[UIView alloc] init];
    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:beginLine];
    
    UIView *endLine = [[UIView alloc] init];
    endLine.frame = CGRectMake(0, KSECTIONHEIGHT-0.5, tableView.frame.size.width, 0.5);
    [endLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:endLine];
    
    UILabel *label = [[UILabel alloc] init];
    if (tableView == _tableView) {
        if (section == 0) {
            if (self.mineGroupArray.count > 0) {
              [label setText:[NSString stringWithFormat:@"我创建的群(%zd)",self.mineGroupArray.count]];
            } else {
            [label setText:[NSString stringWithFormat:@"我加入的群(%zd)",self.otherGroupArray.count]];
            }
        } else {
            [label setText:[NSString stringWithFormat:@"我加入的群(%zd)",self.otherGroupArray.count]];
        }
        
        
    } else {
       label.text = _searchAllFirstLetter[section];
    }
    [label setTextColor:RGBCOLOR(0x92, 0x92, 0x92)];
    label.frame = CGRectMake(15, 1, 200, KSECTIONHEIGHT-2);
    [headerView addSubview:label];
    
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section   // custom view for footer. will be adjusted to default or specified footer height
{
    UIView *headerView = nil;
    if(section == 0)
    {
        return headerView;
    }
    headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, 2);
    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    UIView *beginLine = [[UIView alloc] init];
    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:beginLine];
    return headerView;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = KNORMALCELLHEIGHT;
    
    if(indexPath.row == 0 && indexPath.section == 0)
    {
        height = KNORMALCELLHEIGHT;
    }
    return height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (_tableView == tableView) {
        CGroupModel *model = nil;
        if (indexPath.section == 0) {
            if (self.mineGroupArray.count > 0) {
                model = self.mineGroupArray[indexPath.row];
            } else {
                model = self.otherGroupArray[indexPath.row];
            }
        } else {
            model = self.otherGroupArray[indexPath.row];
        }
        
        
        if (model) {
            CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
            chat.group = model;
            chat.member = nil;
            [self.navigationController pushViewController:chat animated:YES];
        } else {
            
        }
        
    } else {
        NSArray *rowArray = _searchSectionListArray[indexPath.section];
        CGroupModel *model = rowArray[indexPath.row];
        if (model) {
            CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
            chat.group = model;
            chat.member = nil;
            [self.navigationController pushViewController:chat animated:YES];
        } else {
            
        }

    }
    
}

-(void)showMembersDetailVCWithMemeber:(CContactModel *)contact deptName:(NSString *)depName
{
    GroupMemberDetailVC *groupMemberDetail = [[GroupMemberDetailVC alloc] init];
    
    groupMemberDetail.member = contact;
    [self.navigationController pushViewController:groupMemberDetail animated:YES];
    
}


- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleNone;
}
//bug6041
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    
//}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
        return NO;
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(3_0)
{
    return @"删除";
}




//-(void)showGroupDetailVC
//{
//    GroupDetailVC *groupDetail = [[GroupDetailVC alloc] init];
//    CHSNavigationController *departDetailNav = [[CHSNavigationController alloc] initWithRootViewController:groupDetail];
//    //    [self.leveyTabBarController presentViewController:departDetailNav animated:YES completion:nil];
//    [self.navigationController pushViewController:groupDetail animated:YES];
//}
//
//
//
//-(void)showDepartDetailVC
//{
////    DepartDetailVC *departDetail = [[DepartDetailVC alloc] init];
////    CHSNavigationController *departDetailNav = [[CHSNavigationController alloc] initWithRootViewController:departDetail];
////    //    [self.leveyTabBarController presentViewController:departDetailNav animated:YES completion:nil];
////    [self.navigationController pushViewController:departDetail animated:YES];
////    //    [self.leveyTabBarController hidesTabBar:YES animated:NO];
//    
//}
//
//-(void)showGroupListVC
//{
////    GroupListVC *groupList = [[GroupListVC alloc] init];
////    CHSNavigationController *departDetailNav = [[CHSNavigationController alloc] initWithRootViewController:groupList];
////    //    [self.leveyTabBarController presentViewController:departDetailNav animated:YES completion:nil];
////    [self.navigationController pushViewController:groupList animated:YES];
////    //    [self.leveyTabBarController hidesTabBar:YES animated:NO];
//    
//}


#pragma mark-- UISearchBarDelegate
- (void) searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller NS_DEPRECATED_IOS(3_0,8_0)
{
    UIView *topView = controller.searchBar.subviews[0];
    
    for (UIView *subView in topView.subviews) {
        
        if ([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
            
            UIButton * cancelButton = (UIButton*)subView;
            
            [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
            
        }
        
    }
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [_searchSectionListArray removeAllObjects];
    [_searchAllFirstLetter removeAllObjects];
    NSArray *contactArray = [[[CGroupMgr alloc] init] searchGroupWithSeachStr:searchText withGroupType:0];
    if (contactArray.count <= 0) {
        return;
    }
    _searchAllFirstLetter = [NSArray IndexArray:contactArray];
    _searchSectionListArray = [NSArray LetterSortArray:contactArray];
    
    
}
//隐藏搜索为空时cell的分割线
//bug 8510 fixed by lixu
- (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView NS_DEPRECATED_IOS(3_0,8_0){
    [tableView setContentInset:UIEdgeInsetsZero];
    [tableView setScrollIndicatorInsets:UIEdgeInsetsZero];
    tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString

{ for(UIView *subview in controller.searchResultsTableView.subviews) {
    
    if([subview isKindOfClass:[UILabel class]]) {
        
        [(UILabel*)subview setText:@"未找到匹配的信息"];
        
    }
    
}
    return YES;
}


@end
